package com.cw.aspect;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cw.common.constant.Constants;
import com.cw.entity.SysUser;
import com.cw.mapper.SysUserMapper;
import com.cw.util.HttpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Optional;

/**
 * @author qtx
 * @since 2024/1/24
 */
@Aspect
@Component
public class YardAspect {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Pointcut("@annotation(com.cw.annotation.AutoYard)")
    private void pointCut() {
    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        //获得工号
        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
        SysUser sysUser = Optional.ofNullable(sysUserMapper.selectOne(Wrappers.lambdaUpdate(SysUser.class)
                        .eq(SysUser::getUsername, userName)))
                .orElse(new SysUser());
        String yard = sysUser.getYard();
        String strings = getYard(yard);
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg != null) {
                autoYard(arg, strings, "Yard");
                autoYard(arg, strings, "DistrictCode");
            }
        }
    }

    private void autoYard(Object arg, String strings, String parameter) {
        try {
            // 查找对象中是否有 'getYard' 方法
            Method yardGetter = arg.getClass()
                    .getMethod("get" + parameter);
            // 如果找到了这个方法，则调用它并获取 'yard' 值
            if (String.class.equals(yardGetter.getReturnType())) {
                String yardValue = (String) yardGetter.invoke(arg);
                if (StringUtils.isBlank(yardValue)) {
                    Method setYard = arg.getClass()
                            .getMethod("set" + parameter, String.class);
                    setYard.invoke(arg, strings);
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            // 方法不存在或无法访问时，忽略此对象
        }
    }

    private String getYard(String yard) {
        if (yard != null) {
            String[] split = yard.split(",");
            return split.length == 1 ? split[0] : "";
        }
        return "";
    }

}
